package com.rule;

import com.netflix.loadbalancer.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;
import com.netflix.client.config.IClientConfig;

/**
 * @description:
 * @author: sksun2
 * @create: 2023-09-28
 */
public class CustomRule extends AbstractLoadBalancerRule {

    private ILoadBalancer lb;

    public CustomRule() {
    }


    @Override
    public void setLoadBalancer(ILoadBalancer lb){
        this.lb = lb;
    }



    /**
     * 目标：自定义负载均衡策略：从所有可用的provider中排除掉指定端口号的provider，剩余provider进行随机选择
     * 实现步骤：
     * 1.获取到所有Server
     * 2.从所有Server中排除掉指定端口的Server后，剩余的Server
     * 3.从剩余Server中随机选择一个Server
     */
    @Override
    public Server choose(Object key) {
        // 1.获取到所有Server
        List<Server> servers = lb.getReachableServers();
        // 转 NACOS Server

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        final String gray = request.getHeader("gray");

        if(servers.size() > 0){

        }

        return this.getAvailableRandomServers(servers);
    }

    private Server getAvailableRandomServers(List<Server> availableServers) {
        // 获取一个[0,availableServers.size())的随机数
        int index = new Random().nextInt(availableServers.size());
        Server serviceInstance = availableServers.get(index);
        return serviceInstance;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }
}
